package books4africa

import org.springframework.security.authentication.AuthenticationServiceException;

class BookRequestController {
//	def scaffold= true;
	
	def springSecurityService
	def bookRequestService
	
	static navigation = [
		[group:'tabs', action:'list', title:'Requests', order:1],
		]
	
	def index = {
		redirect(action:list)
	}
	
	def list (){
		bookRequestService.listRequests()
	}

	def create(){
		
		[bookRequestInstance: new BookRequest(params)]
	}
	
	def save(){
		
		int requestId
		
		try{
			def user = springSecurityService.getCurrentUser()
			user = User.get(user.id)
			
			def book = Books.get(params.book.id)
			
			requestId = bookRequestService.addToRequests(book, user, params.bookQty.toInteger(), params.description)
			flash.message = "Added new request for  ${book.title}"
		
			} 
		catch (BookRequestException e){
			flash.message = e.message
		}
			
		redirect(action:'show', id: requestId)
		
	}
	
	def show() {
		bookRequestService.showRequest(params.id.toInteger())
	}
	
	
	def siteIndex = {
		
		def results = bookRequestService.siteIndex()
		 
		 render(view:"../index", model:[requestList:results])
		
	}
  
   def last5 = {
		
		 def results = bookRequestService.lastFive()
		 
		 render(template:"../last5", model:[requestList:results])
		
		 }
	
	def search =  {	

		def results = BookRequest.getAll()
		render(view: 'search', model: [bookRequestInstanceList: results])

		}
	
	def ajaxSearch = {

		def results = bookRequestService.aSearch(params)	
			
		render(template: 'results', model: [bookRequestInstanceList: results])
	}
}
